# -*- coding: utf-8 -*-
### BEGIN LICENSE
# This file is in the public domain
### END LICENSE

import gtk

from wau.helpers import get_builder
import ConfigParser
import logging
import settings

import gettext
from gettext import gettext as _
gettext.textdomain('wau')

_config_backend = None

class DataStorer(object):

    def get(self, q):
        return self.config.get(self.settingsname, q)
        
    def put(self, q, v):
        return self.config.set(self.settingsname, q, v)
        
    "Translates data to/from gtk widgets and strings"
    def __init__(self, settings, config, builder, settingsname = "settings"):
        self.builder = builder
        self.settingsname = settingsname
        self.config = config
        self.settings = settings

        self.functionmap = {
            'file': self.func_file_data,
            'bool': self.func_bool_data,
            'entry': self.func_entry_data,
        }

    def load_preferences(self):
        for settingname, stype in self.settings:
            if stype in self.functionmap.keys():
                value = self.config.get(self.settingsname, settingname)
                if value:
                    obj = self.builder.get_object(settingname)
                    self.functionmap[stype](obj, value)

    def save_preferences(self):
        for settingname, stype in self.settings:
            if stype in self.functionmap.keys():
                obj = self.builder.get_object(settingname)
                value = self.functionmap[stype](obj)
                self.config.set(self.settingsname, settingname, value)
        self.config.save()

    def func_entry_data(self, obj, value=None):
        if not value:
            return obj.get_text()
        else:
            return obj.set_text(value)

    def func_bool_data(self, obj, value=None):
        if value == None:
            return obj.get_active()
        else:
            if value == "True":
                value = True
            else:
                value = False
            return obj.set_active(value)

    def func_file_data(self, obj, value=None):
        if not value:
            return obj.get_filename()
        else:
            return obj.set_filename(value)

class IniConfigBackend(object):
    def __init__(self):
        self.inifile = settings.INIFILE
        self._open_file()

    def _open_file(self):
        self.c = ConfigParser.SafeConfigParser()
        self.c.read(self.inifile)

    def section(self, s):
        if not self.c.has_section(s):
            self.c.add_section(s)

    def get(self, *args):
        self.section(args[0])
        if self.c.has_option(*args):
            return self.c.get(*args)
        return False
        
    def set(self, s, o, v):
        logging.debug("Setting : [%s] %s = %s" % (s, o, v))
        self.section(s)
        v = unicode(v)
        self.c.set(s, o, v)
        
    def save(self):
        logging.debug("Writing config file")
        f = open(self.inifile, "wb")
        self.c.write(f)
        f.close()

class PreferencesWauDialog(gtk.Dialog):
    __gtype_name__ = "PreferencesWauDialog"
    preferences = {}

    def __new__(cls):
        """Special static method that's automatically called by Python when 
        constructing a new instance of this class.
        
        Returns a fully instantiated PreferencesWauDialog object.
        """
        builder = get_builder('PreferencesWauDialog')
        new_object = builder.get_object("preferences_wau_dialog")
        new_object.finish_initializing(builder)
        return new_object

    def finish_initializing(self, builder):
        """Called while initializing this instance in __new__

        finish_initalizing should be called after parsing the ui definition
        and creating a PreferencesWauDialog object with it in order to
        finish initializing the start of the new PerferencesWauDialog
        instance.
        
        Put your initialization code in here and leave __init__ undefined.
        """

        # Get a reference to the builder and set up the signals.
        self.settings = [
            ("wowFolder", "file"),
            ('checkupdates', 'bool'),
            ('doupdates', 'bool'),
        ]
        
        self.builder = builder
        self.builder.connect_signals(self)
        
        global _config_backend
        if _config_backend == None:
            _config_backend = IniConfigBackend()
        self.config = _config_backend

        self.store = DataStorer(self.settings, self.config, self.builder)

        self.get_preferences()

    def get_preferences(self):
        """Return a dict of preferences for wau.

        """
        #if self._preferences == None:
            # The dialog is initializing.
        self.store.load_preferences()

        # If there were no saved preference, this.
        return self.config

    def ok(self, widget, data=None):
        """The user has elected to save the changes.

        Called before the dialog returns gtk.RESONSE_OK from run().
        """

        # Make any updates to self._preferences here. e.g.
        #self._preferences["preference1"] = "value2"
        self.store.save_preferences()

    def cancel(self, widget, data=None):
        """The user has elected cancel changes.

        Called before the dialog returns gtk.RESPONSE_CANCEL for run()
        """
        # Restore any changes to self._preferences here.
        self.store.load_preferences()
        pass

if __name__ == "__main__":
    dialog = PreferencesWauDialog()
    dialog.show()
    gtk.main()
